package com.android.mms.sec;

import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.ContactsContract;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

public class AllContactLayout extends FrameLayout {

    private String mSelectPhone;
    private ContactAdapter mAdapter;
    private final AtomicBoolean isAttached = new AtomicBoolean(true);
    private final List<ContactInfo> mItemList = new ArrayList<>();

    public AllContactLayout(Context context) {
        this(context, null, 0);
    }

    public AllContactLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AllContactLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        mAdapter = new ContactAdapter(getContext(), mItemList);
        ListView listView = findViewById(android.R.id.list);

        listView.setAdapter(mAdapter);
        listView.setEmptyView(findViewById(android.R.id.empty));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Object obj = view.getTag();
                if (obj instanceof ContactInfo) {
                    ContactInfo info = (ContactInfo) obj;
                    List<String> phones = info.phoneNumList;
                    final int size = phones.size();
                    if (size == 1) {
                        mSelectPhone = phones.get(0);
                        startCreateNewMessage(mSelectPhone);
                    } else if (size > 1) {
                        String[] items = new String[size];
                        phones.toArray(items);
                        mSelectPhone = items[0];
                        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                        builder.setTitle(info.name);
                        builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mSelectPhone = items[which];
                            }
                        });
                        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (mSelectPhone != null) {
                                    startCreateNewMessage(mSelectPhone);
                                }
                            }
                        });
                        builder.setNegativeButton(android.R.string.cancel, null);
                        builder.show();
                    }
                }
            }
        });

        new Thread(new Runnable() {

            @Override
            public void run() {
                readContacts();
            }
        }).start();
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        isAttached.set(true);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        isAttached.set(false);
    }

    private void startCreateNewMessage(String phone) {
//        Intent intent = new Intent(getContext(), ComposeMessageActivity.class);
//        intent.putExtra("finish", true);
//        intent.setAction(Intent.ACTION_SENDTO);
//        intent.setData(Uri.parse("smsto:" + phone));
//        getContext().startActivity(intent);
    }

    private void readContacts() {
        ContentResolver contentResolver = getContext().getContentResolver();
        Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

        mItemList.clear();
        if (cursor != null && cursor.moveToFirst()) {
            do {
                ContactInfo info = new ContactInfo();

                info.id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                info.name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                int phoneCount = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

                if (phoneCount > 0) {
                    Cursor phoneCursor = getContext().getContentResolver().query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + info.id, null, null);
                    if (phoneCursor.moveToFirst()) {
                        do {
                            String num = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            info.phoneNumList.add(num);
                        } while (phoneCursor.moveToNext());
                    }
                    phoneCursor.close();
                }

                mItemList.add(info);
                if (!isAttached.get()) {
                    break;
                }
            } while (cursor.moveToNext());
        }

        if (isAttached.get()) {
            mItemList.sort(new Comparator<ContactInfo>() {

                @Override
                public int compare(ContactInfo o1, ContactInfo o2) {
                    try {
                        return o1.name.compareTo(o2.name);
                    } catch (Exception ignored) {
                    }
                    return 0;
                }
            });
        }

        if (isAttached.get()) {
            if (getHandler() != null) {
                getHandler().post(new Runnable() {

                    @Override
                    public void run() {
                        if (mAdapter != null) {
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                });
            }
        }
        if (cursor != null) {
            cursor.close();
        }
    }

    private static class ContactInfo {
        String name;
        String id;
        List<String> phoneNumList = new ArrayList<>();
    }

    private static class ContactAdapter extends ArrayAdapter<ContactInfo> {

        private final LayoutInflater mInflater;

        public ContactAdapter(Context context, List<ContactInfo> objects) {
            super(context, -1, objects);
            mInflater = LayoutInflater.from(context);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.sec_all_contact_item_layout, null);
            }

            ImageView imgPhoto = convertView.findViewById(android.R.id.icon);
            TextView textTitle = convertView.findViewById(android.R.id.title);

            ContactInfo info = getItem(position);

//            imgPhoto.setImageDrawable(imgPhoto);
            textTitle.setText(info.name);
            convertView.setTag(info);
            return convertView;
        }
    }
}
